package com.suning.sawp.service.listener;

import java.util.Date;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.suning.rsc.dto.responsedto.MbfServiceResponse;
import com.suning.rsc.mqservice.ei.annotation.EsbEIServerService;
import com.suning.rsc.server.NullResponseDto;
import com.suning.rsc.server.mq.MQServerServiceHandler;
import com.suning.sawp.constants.LoggerConstants;
import com.suning.sawp.dto.common.NsfNullReponseInterfaceForEsb;
import com.suning.sawp.dto.esb.TaskCardInfo;
import com.suning.sawp.dto.esb.TaskCardResponse;
import com.suning.sawp.intf.taskCard.IndexTaskCardService;
import com.suning.sawp.intf.taskCard.dto.TaskCardDto;
import com.suning.sawp.service.util.DateUtils;

/**
 * 首页任务卡信息MQ服务 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 * SnsawpMangement-sendTaskCardNotice
 * @author 15050519
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@EsbEIServerService(connectionFactory = "snsawpConnectionFactory", receiveQueue = "taskCardQueue")
public class TaskCardListener
        extends MQServerServiceHandler<TaskCardResponse, NullResponseDto, NsfNullReponseInterfaceForEsb> {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerConstants.SAWP_INTEGRATION);

    /**
     * 任务卡服务
     */
    @Autowired
    IndexTaskCardService indexTaskCardService;

    /**
     * 处理MQ消息
     */
    @Override
    public NullResponseDto handleBizz(TaskCardResponse resp, String uid) {
        LOGGER.debug("TaskCardListener接收数据：uid:{},resp{}", uid, resp);
        if (null == resp || StringUtils.isBlank(resp.getBizKey()) || CollectionUtils.isEmpty(resp.getTaskCardList())) {
            LOGGER.info("TaskCardListener推送入参不合法:");
            return null;
        }
        // 迭代保存消息
        TaskCardDto dto = null;
        for (TaskCardInfo info : resp.getTaskCardList()) {
            dto = convertTaskCardInfo(info, resp.getBizKey());
            // 保存
            saveTaskCard(dto);
        }

        return null;
    }

    /**
     * 保存任务卡信息
     *
     * @param dto
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private void saveTaskCard(TaskCardDto dto) {
        if (null != dto) {
            try {
                if (StringUtils.isBlank(dto.getStaffId()) || StringUtils.isBlank(dto.getBizKey())
                        || StringUtils.isBlank(dto.getCardType())) {
                    return;
                }
                // 删除任务卡
                indexTaskCardService.delTaskCard(dto.getStaffId(), dto.getBizKey());
                // 保存任务卡
                indexTaskCardService.saveTaskCard(dto);
            } catch (Exception e) {
                LOGGER.error(" TaskCardListener saveTaskCard error, dto=" + dto, e);
            }
        }
    }

    /**
     * 转换任务卡对象 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param info
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private TaskCardDto convertTaskCardInfo(TaskCardInfo info, String bizKey) {
        LOGGER.info(" convertTaskCardInfo info={} ", info);
        if (null != info) {
            TaskCardDto dto = new TaskCardDto();
            dto.setStaffId(info.getStaffId());
            dto.setBizKey(bizKey);
            dto.setCardType(info.getCardType());
            dto.setTitle(info.getTitle());
            dto.setStartTime(convertDate(info.getStartTime()));
            dto.setEndTime(convertDate(info.getEndTime()));
            dto.setTaskStatus(info.getTaskStatus());
            dto.setFirstNum(info.getFirstNum());
            dto.setSecondNum(info.getSecondNum());
            dto.setThirdNum(info.getThirdNum());
            dto.setExt1(info.getExt1());
            dto.setExt2(info.getExt2());
            dto.setExt3(info.getExt3());
            dto.setExt4(info.getExt4());
            dto.setExt5(info.getExt5());
            dto.setPartnumberAmt(info.getPartnumberAmt());
            dto.setCateCode(info.getCateCode());
            dto.setTaskTips(info.getTip());
            dto.setWapLink(info.getWapLink());
            return dto;
        }
        return null;
    }

    /**
     * 时间转换 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param date
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    private Date convertDate(String date) {
        LOGGER.info(" convertDate date={} ", date);
        try {
            return DateUtils.getDateByStr(date, DateUtils.DEFAULT_TIME_PATTERN);
        } catch (Exception e) {
            LOGGER.error("TaskCardListener dateTime convert error", e);
        }
        return null;
    }

    /**
     * 响应为空
     */
    @Override
    public void sendResponse(NsfNullReponseInterfaceForEsb clientInterface, NullResponseDto response,
            MbfServiceResponse serviceResponse) {
        LOGGER.debug("no response");
    }

}
